package com.security.zhl.zuul.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Component
public class PreSendForwardFilter extends ZuulFilter {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    public boolean shouldFilter() {
        return true;
    }

    public Object run() {
        RequestContext requestContext = RequestContext.getCurrentContext();

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(!(authentication instanceof OAuth2Authentication)){
            return null;
        }

        OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) authentication;
        Authentication userAuthentication=oAuth2Authentication.getUserAuthentication();

        List<String> authorities = new ArrayList<>();

        userAuthentication.getAuthorities().stream().forEach(s->authorities.add( ((GrantedAuthority)s).getAuthority()));

        OAuth2Request oAuth2Request = oAuth2Authentication.getOAuth2Request();

        Map<String , String > requestParameters = oAuth2Request.getRequestParameters();


        Map<String , Object > jsonToken = new HashMap<>(requestParameters);

        if (userAuthentication!=null){

            jsonToken.put("principal" , userAuthentication.getName() );
            jsonToken.put( "authorities" , authorities );

        }

        requestContext.addZuulRequestHeader("json-token" , JSON.toJSONString(jsonToken));

        HttpServletRequest request = requestContext.getRequest();
        String host = request.getRemoteHost();
        String method = request.getMethod();
        String uri = request.getRequestURI();
        log.info("请求URI：{}，HTTP Method：{}，请求IP：{}", uri, method, host);
        return null;
    }
}
